﻿using System;
using System.Collections.Generic;

namespace MapleLeaf.IdentityServer.Helper {
    public class JsonHelper {
        /// <summary>
        /// 转换对象为JSON格式数据
        /// </summary>
        /// <typeparam name="T">类</typeparam>
        /// <param name="obj">对象</param>
        /// <returns>字符格式的JSON数据</returns>
        public static string GetJSON<T>(object obj) {
            string result = string.Empty;

            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
            new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
                serializer.WriteObject(ms, obj);
                result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }

            return result;
        }
        /// <summary>
        /// 转换List<T>的数据为JSON格式
        /// </summary>
        /// <typeparam name="T">类</typeparam>
        /// <param name="vals">列表值</param>
        /// <returns>JSON格式数据</returns>
        public string JSON<T>(List<T> vals) {
            System.Text.StringBuilder st = new();

            System.Runtime.Serialization.Json.DataContractJsonSerializer s = new(typeof(T));

            foreach (T city in vals) {
                using System.IO.MemoryStream ms = new();
                s.WriteObject(ms, city);
                st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
            }


            return st.ToString();
        }
        /// <summary>
        /// JSON格式字符转换为T类型的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T ParseFormByJson<T>(string jsonStr) {
            using System.IO.MemoryStream ms =
            new(System.Text.Encoding.UTF8.GetBytes(jsonStr)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new(typeof(T));
            return (T)serializer.ReadObject(ms);
        }

        public string JSON1<SendData>(List<SendData> vals) {
            System.Text.StringBuilder st = new System.Text.StringBuilder();

            System.Runtime.Serialization.Json.DataContractJsonSerializer s = new(typeof(SendData));

            foreach (SendData city in vals) {
                using System.IO.MemoryStream ms = new System.IO.MemoryStream(); s.WriteObject(ms, city);
                st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
            }
            return st.ToString();
        }
    }
}
